<template>
   <div class="setting-container towColumn">
    <s-card title="网络设置">
         <s-form :label-col="2">
            <s-form-item label="网络模式">
               <s-select
                  :value="state.sysInfo['network-mode']"
                  name="network-mode"
                  @update="handleUpdate"
                  @focus="handleFocus"
                  @blur="handleBlur"
               >
                  <option :value="0">Static</option>
                  <option :value="1">DHCP</option>
               </s-select>
            </s-form-item>
            <s-form-item label="IP地址">
               <s-input
                  name="address"
                  :value="state.sysInfo.address"
                  @update="handleUpdate"
                  :disabled="disabled"
                  @blur="handleBlur"
                  @focus="handleFocus"
               />
            </s-form-item>
            <s-form-item label="子网掩码">
               <s-input
                  name="subnetmask"
                  :value="state.sysInfo.subnetmask"
                  @update="handleUpdate"
                  :disabled="disabled"
                  @blur="handleBlur"
                  @focus="handleFocus"
               />
            </s-form-item>
            <s-form-item label="网关">
               <s-input
                  name="gateway"
                  :value="state.sysInfo.gateway"
                  @update="handleUpdate"
                  :disabled="disabled"
                  @blur="handleBlur"
                  @focus="handleFocus"
               />
            </s-form-item>
         </s-form>
         <template #footer>
            <s-button type="primary" @click="handleNet">应用</s-button>
        </template>
      </s-card>

      <s-card title="接入平台">
         <s-form :label-col="2">
            <s-form-item label="状态">
               <s-badge :type="platformStatus[0]">
                  {{ platformStatus[1] }}
               </s-badge>
            </s-form-item>
            <s-form-item label="IP地址">
               <s-input
                  name="platform_ip"
                  :value="state.sysInfo.platform_ip"
                  @update="handleUpdate"
                  @blur="handleBlur"
                  @focus="handleFocus"
               />
            </s-form-item>
            <s-form-item label="IP端口">
               <s-input
                  name="platform_port"
                  :value="state.sysInfo.platform_port"
                  @update="handleUpdate"
                  @blur="handleBlur"
                  @focus="handleFocus"
               />
            </s-form-item>
            <s-form-item label="4G地址">
               <s-input
                  name="platform_4g_addr"
                  :value="state.sysInfo.platform_4g_addr"
                  @update="handleUpdate"
                  @blur="handleBlur"
                  @focus="handleFocus"
               />
            </s-form-item>
            <s-form-item label="4G端口">
               <s-input
                  name="platform_4g_port"
                  :value="state.sysInfo.platform_4g_port"
                  @update="handleUpdate"
                  @blur="handleBlur"
                  @focus="handleFocus"
               />
            </s-form-item>

         </s-form>
         <template #footer>
            <s-button type="primary" @click="handlePlatform">应用</s-button>
        </template>
      </s-card>

      <insert-audio-setting/>
      <s-card title="重启/恢复出厂设置/升级">
         <s-form-item label="定时重启间隔" :label-col="2">
            <s-select :value="state.sysInfo.itervaltime" name="itervaltime" width="100px" @update="handleUpdate" @focus="handleFocus"  @blur="handleBlur">
               <option :value="0">不重启</option>
               <option :value="1">1天</option>
               <option :value="2">2天</option>
               <option :value="3">3天</option>
               <option :value="4">4天</option>
               <option :value="5">5天</option>
               <option :value="6">6天</option>
               <option :value="7">7天</option>
            </s-select>
            <s-button
               type="primary"
               @click="handleInterval"
               style="margin-left: 16px"
               >设置</s-button
            >
         </s-form-item>
         <reboot-default/>
         <s-form-item label="升级" :label-col="2">
            <version-upgrade/>
         </s-form-item>
      </s-card>
      <s-card title="音量设置">
         <s-form :label-col="2">
            <s-form-item label="音量">
               <s-input
                  name="vol"
                  :value="state.sysInfo.vol"
                  type="number"
                  help="[0-100]"
                  @update="handleUpdate"
                  @blur="handleBlur"
                  @focus="handleFocus"
                  :disabled="!state.showVol"
               />
               <s-button
               type="primary"
               @click="handleVol"
               style="margin-left: 16px"
               :disabled="!state.showVol"
               >设置</s-button
            >
            </s-form-item>
         </s-form>
      </s-card>
      <config-setting/>
      <priority-setting/>
      <pwd-editor/>

      <s-card title="IP音源" v-if="state.showIpSignal">
         <s-checkbox name="ipSignal" :checked="Boolean(state.ipSignal)" @update="handleUpdate" label="开启"/>
      </s-card>

   </div>
</template>

<script lang="ts" setup>
import { isVol, isIp, isPort, Timer, NET_TIME } from "@/utils"
import { VersionUpgrade, ConfigSetting, PwdEditor, RebootDefault, PrioritySetting, InsertAudioSetting } from "@/commomCom"
import { onBeforeMount, reactive, computed, onBeforeUnmount } from "vue"
import {
   SCard,
   SForm,
   SFormItem,
   SBadge,
   SInput,
   SSelect,
   SButton,
   Message,
   SCheckbox
} from "@/components"
import { getSysInfo, setRebootInterval, setVol, setPlatform, setNet, getInEnable, setInEnable } from "@/request"
interface SysInfo {
   platform_ip: string;
   platform_port: number;
   platform_status: number;
   platform_4g_addr: string;
   platform_4g_port: number;

   // 音量设置
   vol: number;

   // 网络设置
   address: string;
   subnetmask: string;
   gateway: string;
   "network-mode": string;

   // 一般操作
   itervaltime: number;
}

let oldIp = ""
const state = reactive<{
      sysInfo: SysInfo,
      ipSignal:number,
      showIpSignal:boolean,
      showVol:boolean
   }>({
      sysInfo: {
         platform_ip: "", // 接入平台 ip
         platform_port: 0, // 接入平台 端口
         platform_status: 0, // 接入平台 状态
         platform_4g_addr: "",
         platform_4g_port: 0,
         vol: 0,
         address: "", // ip
         subnetmask: "", // 子网掩码
         gateway: "", // 网关
         "network-mode": "", // 模式
         itervaltime: 0
      },
      ipSignal: 0,
      showIpSignal: false,
      showVol: false
   })

const deviceType = localStorage.getItem("type")
const isSpecial = deviceType === "WL301 网络功率放大器" || deviceType === "WL302 网络功率放大器"
const disabled = computed(() => {
   return Number(state.sysInfo["network-mode"]) === 1
})

// 接入平台状态
const platformStatus = computed(() => {
   if (state.sysInfo.platform_status === 1) {
      return ["success", "锁定"]
   } else {
      return ["danger", "未锁定"]
   }
})

const getIpSource = () => {
   getInEnable().then((data) => {
      if (data) {
         state.ipSignal = data.IpPlayEnable
      }
   })
}

// 更新数值
const handleUpdate = (params:{name:string, value:any}) => {
   if (params.name === "ipSignal") {
      state.ipSignal = Number(params.value)
      setInEnable({
         IpPlayEnable: state.ipSignal
      }).then((data) => {
         if (data) {
            Message.success("设置成功")
         }
      })
   } else if (params.name === "itervaltime") {
      state.sysInfo[params.name] = Number(params.value)
   } else {
      state.sysInfo[params.name] = params.value
   }
   console.log(state)
}

// 定时重启设置
const handleInterval = () => {
   setRebootInterval({
      itervaltime: Number(state.sysInfo.itervaltime)
   }).then(data => {
      if (data) {
         Message.success("设置成功")
      }
   })
}

// 提交接入平台
const handlePlatform = () => {
   const { platform_ip, platform_port, platform_4g_addr, platform_4g_port } = state.sysInfo
   console.log({
      pPlatform: {
         address: platform_ip,
         cmdport: Number(platform_port),
         "4g_address": platform_4g_addr,
         "4g_cmdport": Number(platform_4g_port)
      }
   })
   if (isIp(platform_ip) && isPort(platform_port) && isIp(platform_4g_addr) && isPort(platform_4g_port)) {
      setPlatform({
         pPlatform: {
            address: platform_ip,
            cmdport: Number(platform_port),
            "4g_address": platform_4g_addr,
            "4g_cmdport": Number(platform_4g_port)
         }
      }).then(data => {
         data && Message.success("设置成功！")
      })
   } else {
      Message.error("格式错误，请重新检查！")
   }
}

// 提交网络设置
const handleNet = () => {
   const { address, subnetmask, gateway } = state.sysInfo
   const mode = Number(state.sysInfo["network-mode"])
   if ((isIp(address) && isIp(subnetmask) && isIp(gateway) && mode === 0) || mode === 1) {
      setNet({
         "network-mode": mode,
         address,
         subnetmask,
         gateway
      }).then((data) => {
         if (data) {
            // 静态时判断ip是否改变
            if (mode === 0) {
               if (oldIp !== address) {
                  Message.success("设置成功,稍后将进行跳转...")
                  Timer.netChange = setTimeout(() => {
                     localStorage.setItem("token", "")
                     window.location.href = `http://${address}`
                  }, NET_TIME)
               } else {
                  Message.success("设置成功")
                  refreshSysInfo()
               }
            } else {
               Message.success("设置成功,稍后将进行跳转...")
               Timer.netChange = setTimeout(() => {
                  localStorage.setItem("token", "")
                  window.location.href = `http://${data.ip}`
               }, NET_TIME)
            }
         }
      })
   } else {
      Message.error("格式错误，请重新检查！")
   }
}

const refreshSysInfo = () => {
   getSysInfo().then((data) => {
      state.sysInfo = data
      oldIp = data.address
      state.showVol = data.judgeknob === 0
   })
}

const handleBlur = () => {
   Timer.refreshSysInfo = setInterval(() => {
      refreshSysInfo()
   }, 3000)
}

const handleFocus = () => {
   clearInterval(Timer.refreshSysInfo)
}

// 音量设置
const handleVol = () => {
   if (isVol(state.sysInfo.vol)) {
      setVol({
         vol: Number(state.sysInfo.vol)
      }).then(res => {
         if (res) {
            Message.success("设置成功")
         }
      })
   } else {
      Message.error("音量输入有误，范围为[0,100]！")
   }
}
onBeforeUnmount(() => {
   clearInterval(Timer.refreshSysInfo)
   clearTimeout(Timer.netChange)
})
onBeforeMount(() => {
   refreshSysInfo()
   Timer.refreshSysInfo = setInterval(() => {
      refreshSysInfo()
   }, 3000)
   if (isSpecial) {
      getIpSource()
      state.showIpSignal = true
   }
})
</script>

<style scoped lang="less">
   .setting-container {
   }
</style>
